package net.chrisrichardson.ec2deployer.core;

import net.chrisrichardson.ec2deployer.util.FileBasedTemplate;

public abstract class Application {

  long id
  EC2Server host
  List clientApplications = []
  List requiredApplications = []

  protected Application() {

  }
  
  Application(host)  {
	  this.host = host
  }
  
  def addRequiredApplication(requiredApplication)  {
	  requiredApplications.add(requiredApplication)
	  requiredApplication.addClientApplication(this)
  }

  public addClientApplication(Application clientApplication) {
	clientApplications.add(clientApplication)
  }


  public String getHostPrivateDnsName() {
      return host.privateDnsName
  }

    def writeFile(Map _args) {
        def fileName = _args["fileName"]
        def templateName = _args["templateName"]
        def args = _args["templateArgs"]

        FileBasedTemplate template = new FileBasedTemplate()
        def text = template.process(templateName, args)
        host.ssh("cat > $fileName", text)
    }
    def appendToFile(Map _args) {
        def fileName = _args["fileName"]
        def text = _args["text"]
        host.ssh("cat >> $fileName", text);
    }

    def startService(String serviceName) {
        host.ssh("/sbin/service $serviceName start")
    }

    def restartService(String serviceName) {
        host.ssh("/sbin/service $serviceName restart")
    }

    def stopService(serviceName) {
        host.ssh("/sbin/service $serviceName stop")
	}

    def waitForHttp(Map _args) {
        def port = _args["port"]
        def path = _args["path"]
        def scheme = _args["scheme"]
        if (!scheme) scheme = "http"
        if (!port) {
            if (scheme == "https")
                port = 443
            else
                port = 80
        }
        host.ssh("wget ${scheme == "https" ? "--no-check-certificate " : ""}--spider --tries=10 --retry-connrefused --waitretry=10 $scheme://localhost:$port/$path")
	}                 
	
    def exec(command, String text = null) {
        if (text)
        host.ssh(command, text)
        else
        host.ssh(command)
    }

    def exec(Map _args) {
        def command = _args["command"]
        def templateName = _args["templateName"]
        def args = _args["templateArgs"]

        FileBasedTemplate template = new FileBasedTemplate()
        def text = template.process(templateName, args)

        exec command, text
    }

  def startSar() {
      host.startSar()
  }

  def stopSar() {
      host.stopSar()
  }

  def getSarMonitor() {
      host.sarMonitor
  }
}